<?php

namespace App\Models\Knowledge;

use App\Models\Flaw\Category;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;

class KnowledgeMsg extends Model
{
    protected $table = 'klg_msg';

    protected $primaryKey = 'id';

    protected $fillable = [];

    protected $guarded = [];

    public $timestamps = true;


    public function rules ($request){
        return [
            'klg_id'       => [Rule::exists('knowledge','id')->where(function ($query) {
                $query->where('id', '!=', 0);
            })],
            'user_id'      => [Rule::exists('users','id')->where(function ($query) {
                $query->where('id', '!=', 0);
            })],
            'msg' => 'required'
        ];
    }

    public function messages (){
        return [
            'klg_id.exists'      => '非法操作',
            'user_id.exists'      => '非法操作',
            'msg.required' => '留言不能为空',
        ];
    }

    public function validate ($request){
        return Validator::make($request->all(),
            $this->rules($request),
            $this->messages()
        );
    }

    /**
     * store msg
     * @param $request
     * @throws \Exception
     * @return bool
     */
    public function store ($request){
        $data = $request->all();
        $data['klg_id']    = intval($request->klg_id);
        $user = Auth::user();
        $data['user_id']   = $user->id;
        $data['user_name'] = $user->real_name;
        $data['user_email']= decrypt_func($user->email,$user->name);
        $data['msg'] = clean($request->msg, 'user_topic_body');
        $id = $this->create($data)->id;
        if ($id <= 0){
            throw new \Exception('评论失败！');
        }
        return true;
    }

    /**
     * getMsg
     */
    public function getMsg ($request) {
        $where['klg_id'] = intval($request->id);
        return $this->where($where)->orderByDesc('top')->orderByDesc('sort')->orderByDesc('created_at')->get();
    }

    /**
     * setTop
     */
    public function setTop($request){
        $msg = $this->find($request->id);
        $msg->top = 1;
        return $msg->save();
    }

}
